package com.koron.common.core.interceptor;

import com.koron.bean.base.Response;
import com.koron.common.core.util.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


@RestControllerAdvice
@Slf4j
public class ResponseInterceptor implements ResponseBodyAdvice<Object> {

    // return true表示对响应进行处理，你可以用returnType来做判断什么时候不需要做处理
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object resBody, MethodParameter arg1, MediaType arg2, Class arg3, ServerHttpRequest req,
                                  ServerHttpResponse res) {
        try {
            if(resBody instanceof Response) {
                Response response = (Response) resBody;
                response.setDescription(CommonUtils.converMsgByLanguage(response.getDescription()));
                return response;
            }
        } catch (Exception e) {
            log.error("语种转化失败",e);
        }
        return resBody;
    }

}
